const { app, BrowserWindow, Menu, session, ipcMain, desktopCapturer } = require('electron');
const path = require('path');
const fs = require('fs');
const http = require('http');
const url = require('url');

let mainWindow;
let localServer;
let appConfig = {};
let currentEnvironment = 'production'; // 默认环境

// 启动本地服务
function startLocalServer(port = 24678) {
    return new Promise((resolve, reject) => {
        const server = http.createServer((req, res) => {
            const parsedUrl = url.parse(req.url, true);
            const pathname = parsedUrl.pathname;

            console.log(`[LocalServer] 请求: ${pathname}`);

            // 处理 /mio.html 请求
            if (pathname === '/mio.html' || pathname === '/mio') {
                serveMioHtml(res);
            }
            // 处理静态资源
            else if (pathname.startsWith('/static/')) {
                serveStaticFile(res, pathname);
            }
            else {
                // 默认返回 mio.html
                serveMioHtml(res);
            }
        });

        server.listen(port, '127.0.0.1', (err) => {
            if (err) {
                reject(err);
                return;
            }
            console.log(`✅ 本地服务已启动: http://127.0.0.1:${port}`);
            localServer = server;
            resolve(server);
        });

        server.on('error', (err) => {
            console.error('❌ 本地服务启动失败:', err);
            reject(err);
        });
    });
}

// 提供 mio.html 内容
function serveMioHtml(res) {
    try {
        // 读取本地的 mio.html 文件
        const mioHtmlPath = path.join(__dirname, 'resources', 'mio', 'mio.html');
        const content = fs.readFileSync(mioHtmlPath, 'utf8');

        res.writeHead(200, {
            'Content-Type': 'text/html; charset=utf-8',
            'Access-Control-Allow-Origin': '*'
        });
        res.end(content);
        console.log('[LocalServer] 已提供本地 mio.html');
    } catch (error) {
        res.writeHead(500, { 'Content-Type': 'text/plain' });
        res.end('Error loading mio.html: ' + error.message);
        console.error('❌ 加载 mio.html 失败:', error);
    }
}

// 提供静态文件
function serveStaticFile(res, pathname) {
    try {
        const filePath = path.join(__dirname, 'resources', 'mio', pathname.replace('/static/', ''));
        const content = fs.readFileSync(filePath);

        // 根据文件类型设置 Content-Type
        const ext = path.extname(filePath).toLowerCase();
        const contentTypes = {
            '.js': 'application/javascript',
            '.css': 'text/css',
            '.png': 'image/png',
            '.jpg': 'image/jpeg',
            '.jpeg': 'image/jpeg',
            '.gif': 'image/gif',
            '.svg': 'image/svg+xml',
            '.html': 'text/html'
        };

        res.writeHead(200, {
            'Content-Type': contentTypes[ext] || 'text/plain',
            'Access-Control-Allow-Origin': '*'
        });
        res.end(content);
    } catch (error) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('File not found');
    }
}

function createWindow() {
    console.log('🪟 创建主窗口...');

    const preloadPath = path.join(__dirname, 'preload.js');
    console.log('📄 预加载脚本路径:', preloadPath);
    console.log('📄 预加载脚本是否存在:', fs.existsSync(preloadPath));
    console.log(`[main] 当前环境: ${currentEnvironment}`);

    // 如果文件不存在，列出当前目录查看
    if (!fs.existsSync(preloadPath)) {
        console.error('❌ preload.js 不存在！');
        const files = fs.readdirSync(__dirname);
        console.log('📂 当前目录文件:', files);
    }

    // 解决私有网络请求限制
    app.commandLine.appendSwitch('disable-features', 'BlockInsecurePrivateNetworkRequests');

    mainWindow = new BrowserWindow({
        width: 1400,
        height: 800,
        minWidth: 800,
        webPreferences: {
            preload: preloadPath,
            contextIsolation: true,
            nodeIntegration: false,
            webviewTag: true,
            webSecurity: false,
            allowRunningInsecureContent: true,
            nativeWindowOpen: true
        },
        icon: path.join(__dirname, 'resources', 'icon.ico')
    });

// 加载主窗口HTML
    mainWindow.loadFile('index.html');
//mainWindow.webContents.openDevTools();

// 窗口显示后强制同步尺寸
    mainWindow.on('show', () => {
        setTimeout(() => {
            mainWindow.setSize(1400, 800);
            mainWindow.center();
        }, 100);
    });
    
    // 向渲染进程传递配置信息
    mainWindow.webContents.on('did-finish-load', () => {
        const apiUrl = getApiUrl();
        mainWindow.webContents.send('config-update', {
            apiUrl: apiUrl,
            environment: currentEnvironment
        });
        console.log('[main] 已发送配置到渲染进程:', { apiUrl, environment: currentEnvironment });
    });

// 处理弹窗窗口配置 - 强制所有链接都在主窗口打开
    mainWindow.webContents.setWindowOpenHandler(({ url }) => {
        console.log('[main] 拦截到新窗口请求，强制在主窗口打开:', url);

        // 立即在主窗口加载目标URL
        mainWindow.loadURL(url);

        // 拒绝创建新的BrowserWindow
        return { action: 'deny' };
    });

// 额外安全措施：拦截所有导航请求，确保都在主窗口进行
    mainWindow.webContents.on('will-navigate', (event, navigationUrl) => {
        console.log('[main] 拦截到导航请求:', navigationUrl);
        // 允许所有导航，因为我们已经强制在主窗口打开
        // 这里可以添加额外的URL验证逻辑
    });

// 处理webview标签（如果需要）
    mainWindow.webContents.on('did-attach-webview', (event, webContents) => {
        console.log('[main] webview已附加');

        // 确保webview内的链接也在主窗口打开
        webContents.setWindowOpenHandler(({ url }) => {
            console.log('[main] webview内拦截到新窗口请求:', url);
            mainWindow.loadURL(url);
            return { action: 'deny' };
        });
    });

// 窗口关闭事件
    mainWindow.on('closed', () => {
        mainWindow = null;
    });

// 可选：添加键盘快捷键处理，防止浏览器默认行为
    mainWindow.webContents.on('before-input-event', (event, input) => {
        // 阻止Ctrl+T等浏览器快捷键
        if (input.control && input.key === 't') {
            event.preventDefault();
        }
        if (input.control && input.key === 'n') {
            event.preventDefault();
        }
    });

    // 应用菜单配置
    const template = [
        {
            label: '视图',
            submenu: [
                {
                    label: '返回',
                    accelerator: 'Alt+Left',
                    click: () => {
                        if (mainWindow && mainWindow.webContents.canGoBack()) {
                            mainWindow.webContents.goBack();
                        }
                    }
                },
                { role: 'reload' },
                { role: 'forceReload' },
                { type: 'separator' },
                { role: 'resetZoom' },
                { role: 'zoomIn' },
                { role: 'zoomOut' },
                { type: 'separator' },
                { role: 'togglefullscreen' }
            ]
        },
        {
            label: '帮助',
            submenu: [{
                label: '关于',
                click() {
                    require('electron').dialog.showMessageBox({
                        type: 'info',
                        title: '关于Mio-Fun',
                        message: '作者：B站UP主 dullwolf蠢狼\n版本 1.0.5',
                        buttons: ['确定']
                    });
                }
            }]
        }
    ];

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
    
    // 保存菜单引用，用于后续控制显示/隐藏
    global.mainMenu = menu;
}

// 在 main.js 中确保有这个 IPC 处理器
ipcMain.handle('desktop-capturer:get-sources', async (event, options) => {
    console.log('[main] 收到桌面捕捉源请求，参数：', options);
    try {
        const { desktopCapturer } = require('electron');
        const sources = await desktopCapturer.getSources(options);
        console.log('[main] 成功获取来源，数量：', sources.length);

        // 处理来源数据
        return sources.map(source => ({
            id: source.id,
            name: source.name || '未命名窗口',
            thumbnail: source.thumbnail ? source.thumbnail.toDataURL() : ''
        }));
    } catch (error) {
        console.error('[main] 获取来源失败：', error);
        throw error;
    }
});

// 添加本地资源获取 IPC
ipcMain.handle('get-local-resource', (event, resourcePath) => {
    const fullPath = path.join(__dirname, 'resources', 'mio', resourcePath);
    return new Promise((resolve, reject) => {
        fs.readFile(fullPath, 'utf8', (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
});

// 媒体权限处理
function setupPermissionHandlers() {
    const globalSession = session.defaultSession;

    globalSession.setPermissionRequestHandler((webContents, permission, callback) => {
        const allowedPermissions = ['media', 'desktop-capture', 'display-capture', 'audioCapture'];
        if (allowedPermissions.includes(permission)) {
            console.log(`[main] 允许权限请求: ${permission}`);
            callback(true);
            return;
        }
        console.log(`[main] 拒绝权限请求: ${permission}`);
        callback(false);
    });

    globalSession.setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
        const allowed = ['media', 'desktop-capture', 'display-capture', 'audioCapture'].includes(permission);
        console.log(`[main] 检查权限 ${permission} for ${requestingOrigin}: ${allowed}`);
        return allowed;
    });

    // 额外的媒体权限设置
    // globalSession.setDisplayMediaRequestHandler((webContents, request, callback) => {
    //     console.log('[main] 处理显示媒体请求');
    //     callback({ audio: 'true', video: 'true' });
    // });
}

// Cookie处理
function setupUniversalCookieHandler() {
    // 可添加CookieCookie处理逻辑
}

// 读取配置文件
function loadConfig() {
    try {
        const configPath = path.join(__dirname, 'resources', 'config.json');
        console.log('[main] 尝试加载配置文件:', configPath);
        
        if (!fs.existsSync(configPath)) {
            console.error('❌ 配置文件不存在:', configPath);
            return null;
        }
        
        const configData = fs.readFileSync(configPath, 'utf8');
        const config = JSON.parse(configData);
        console.log('[main] 配置文件加载成功');
        return config;
    } catch (error) {
        console.error('❌ 加载配置文件失败:', error);
        return null;
    }
}

// 获取当前环境的API URL
function getApiUrl() {
    // 检查命令行参数
    const args = process.argv.slice(2);
    if (args.includes('--dev') || args.includes('-d')) {
        currentEnvironment = 'development';
        console.log('[main] 通过命令行参数设置为开发环境');
    }
    
    // 检查环境变量
    if (process.env.NODE_ENV === 'development') {
        currentEnvironment = 'development';
        console.log('[main] 通过环境变量设置为开发环境');
    }
    
    // 从配置文件获取URL并组合
    if (appConfig && appConfig.environments && appConfig.environments[currentEnvironment]) {
        const envConfig = appConfig.environments[currentEnvironment];
        const baseUrl = envConfig.baseUrl || '';
        const path = envConfig.path || '';
        
        // 确保URL组合正确，避免重复的斜杠
        let fullUrl = baseUrl;
        if (path && !baseUrl.endsWith('/') && !path.startsWith('/')) {
            fullUrl += '/';
        }
        fullUrl += path;
        
        return fullUrl;
    }
    
    // 默认返回生产环境URL
    return 'http://43.132.146.198:8081/mio3';
}

// 应用初始化
app.whenReady().then(async () => {
    console.log('[main] 应用就绪');
    
    // 加载配置
    appConfig = loadConfig();
    
    try {
        // 启动本地服务
        await startLocalServer(24678);
        console.log('✅ 本地服务启动成功');
    } catch (error) {
        console.error('❌ 本地服务启动失败:', error);
        // 即使本地服务启动失败，也继续运行应用
    }

    setupPermissionHandlers();
    setupUniversalCookieHandler();
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });
});

// 所有窗口关闭时退出应用
app.on('window-all-closed', () => {
    if (localServer) {
        localServer.close();
        console.log('🔚 本地服务已停止');
    }
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

// 在现有的 ipcMain.handle 后面添加以下代码

// 窗口控制 IPC
ipcMain.handle('window:minimize', () => {
    if (mainWindow) mainWindow.minimize();
});

ipcMain.handle('window:maximize', () => {
    if (mainWindow) {
        if (mainWindow.isMaximized()) {
            mainWindow.unmaximize();
        } else {
            mainWindow.maximize();
        }
    }
});

ipcMain.handle('window:close', () => {
    if (mainWindow) mainWindow.close();
});

// 对话框 IPC
ipcMain.handle('dialog:show-save-dialog', async (event, options) => {
    const { dialog } = require('electron');
    const result = await dialog.showSaveDialog(mainWindow, options);
    return result;
});

ipcMain.handle('dialog:show-open-dialog', async (event, options) => {
    const { dialog } = require('electron');
    const result = await dialog.showOpenDialog(mainWindow, options);
    return result;
});

// 应用信息 IPC
ipcMain.handle('app:get-version', () => {
    return app.getVersion();
});

// 获取配置信息 IPC
ipcMain.handle('config:get-api-url', () => {
    return getApiUrl();
});

ipcMain.handle('config:get-environment', () => {
    return currentEnvironment;
});

// 控制菜单栏可见性
ipcMain.handle('menu:set-visibility', (event, visible) => {
    console.log('[main] 设置菜单栏可见性:', visible);
    if (visible) {
        Menu.setApplicationMenu(global.mainMenu);
    } else {
        Menu.setApplicationMenu(null);
    }
    return true;
});

// 弹窗窗口通信处理
ipcMain.on('send-to-webview', (event, webContentsId, channel, data) => {
    const targetWebContents = webContents.fromId(webContentsId);
    if (targetWebContents) {
        targetWebContents.send(channel, data);
    }
});